package cj.hrm.controller;


import cj.hrm.entity.Status;
import cj.hrm.entity.User;
import cj.hrm.service.HrmService;
import cj.hrm.util.common.HrmConstants;
import cj.hrm.util.common.RandomCode;
import cj.hrm.util.common.SessionSave;
import cj.hrm.util.page.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    @Qualifier("HrmService")
    private HrmService hrmService;//接口实现类对象

    //处理登录请求
    @RequestMapping(value = "/login")
    public ModelAndView login(@RequestParam("loginname") String loginname,
                              @RequestParam("password") String password,
                              HttpSession session,
                              ModelAndView mv, HttpServletRequest request) {
        // 调用业务逻辑组件判断用户是否可以登录
        User user = hrmService.login(loginname, password);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (user != null) {
            session.setAttribute("token", RandomCode.getRandomCode());
            session.setAttribute("lang", "zh_CN");

            mv.addObject("token", RandomCode.getRandomCode());
            mv.addObject("lang", "zh_CN");

            //
            // 将用户保存到HttpSession当中
            session.setAttribute(HrmConstants.USER_SESSION, user);
            // 客户端跳转到index页面
            mv.setViewName("redirect:/index");
            System.out.println("登录用户：" + loginname);
            System.out.println("登录时间：" + df.format(new Date()));
        } else {
            // 设置登录失败提示信息
            mv.addObject("message", "登录名或密码错误!请重新输入");
            // 服务器内部跳转到登录页面
            mv.setViewName("forward:/loginForm");
        }
        return mv;

    }

    //处理查询请求：
    @RequestMapping(value = "/user/selectUser")
    public String selectUser(Integer pageIndex,
                             @ModelAttribute User user,
                             Model model) {
        System.out.println("user = " + user);
        //创建分页对象
        PageModel pageModel = new PageModel();
        if (pageIndex != null) {
            pageModel.setPageIndex(pageIndex);
        }
        /** 查询用户信息 */
        List<User> users = hrmService.findUser(user, pageModel);
        model.addAttribute("users", users);
        model.addAttribute("pageModel", pageModel);
        return "user/user";
    }
    //处理添加请求
    @RequestMapping(value="/user/addUser")
    public ModelAndView addUser(
            String flag,
            @ModelAttribute User user,
            ModelAndView mv){
        if(flag.equals("1")){
            // 设置跳转到添加页面
            mv.setViewName("user/showAddUser");
        }else{
            // 执行添加操作
            hrmService.addUser(user);
            // 设置客户端跳转到查询请求
            mv.setViewName("redirect:/user/selectUser");
        }
        // 返回
        return mv;
    }
    //修改用户请求:String flag 标记， 1表示跳转到修改页面，2表示执行修改操作;
    //User user  要修改用户的对象
    @RequestMapping(value="/user/updateUser")
    public ModelAndView updateUser(
            String flag,
            @ModelAttribute User user,
            ModelAndView mv){
        if(flag.equals("1")){
            // 根据id查询用户
            User target = hrmService.findUserById(user.getId());
            // 设置Model数据
            mv.addObject("user", target);
            // 返回修改员工页面
            mv.setViewName("user/showUpdateUser");
        }else{
            // 执行修改操作
            hrmService.modifyUser(user);
            // 设置客户端跳转到查询请求
            mv.setViewName("redirect:/user/selectUser");
        }
        // 返回
        return mv;
    }
    @RequestMapping(value="/user/")
    public ModelAndView index2(ModelAndView mv){
        mv.setViewName("/user/list");
        return mv;
    }

    // 如果在目录下输入任何不存在的参数，则跳转到list
    @RequestMapping(value="/user/{formName}")
    public String index2(@PathVariable String formName){
        String blank = "/user/list";
        return blank;
    }

    //查询所有用户显示用户列表
    @RequestMapping(value="/user/list",method=RequestMethod.GET)
    public String index(Integer pageIndex, Model model, String content, User user){
        // 创建分页对象
        PageModel pageModel = new PageModel();
        if(pageIndex != null){
            pageModel.setPageIndex(pageIndex);
        }
        List<User> user_list = hrmService.get_UserList(user,pageModel);
        Integer count = 0;
        if (content!=null&&!content.equals("")){
            count = hrmService.countUser(content);
            user_list = hrmService.get_UserLikeList(content);
        }
        model.addAttribute("count",count);
        model.addAttribute("list",user_list);
        model.addAttribute("pageModel", pageModel);
        return "user/list";
    }


    @RequestMapping(value="/user/toadd",method=RequestMethod.GET)
    public String add(Model model,Integer id){
        if(id!=null){
            User user = hrmService.findUserById(id);
            model.addAttribute("job",user);
        }
        return "/user/add";
    }

    //用户更新页面跳转
    @RequestMapping(value="/user/edit",method=RequestMethod.GET)
    public String edit(Model model,Integer id){
        if(id!=null){
            User user = hrmService.findUserById(id);
            user.setPassword(user.getPassword().substring(0, 6));
            model.addAttribute("user",user);
        }

        List<Status>  status_list = hrmService.findAllStatus();
        model.addAttribute("status_list", status_list);
        return "/user/edit";
    }

    //用户更新操作
    @RequestMapping(value="/user/edit",method=RequestMethod.POST)
    public String toedit(Integer status_id,Integer pageIndex,Model model,Integer id,@ModelAttribute User user){

        PageModel pageModel = new PageModel();
        if(pageIndex != null){
            pageModel.setPageIndex(pageIndex);
        }
        this.genericAssociation(status_id,user);
        hrmService.modifyUser(user);

        List<User> user_list = hrmService.get_UserList(user,pageModel);
        model.addAttribute("list",user_list);
        model.addAttribute("pageModel", pageModel);
        return "redirect:/user/list";
    }
    @RequestMapping(value="/exit")
    public ModelAndView Exit(ModelAndView mv,HttpSession session) {
        mv.setViewName("forward:/loginForm");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("退出系统时间："+df.format(new Date()));
        /*UserVisit us = UserVisitSingleton.getInstance();
        us.setExit_time(df.format(new Date()).toString());
        hrmService.insert_UserVisitInfo(us);*/
        User user = (User) session.getAttribute(HrmConstants.USER_SESSION);
        SessionSave.getSessionIdSave().remove(user.getLoginname());
        session.invalidate();
        return mv;
    }
    private void genericAssociation(Integer status_id,User user){

        if(status_id != null){
            Status status = new Status();
            status.setId(status_id);
            user.setStatus(status);
        }
    }

		/*@RequestMapping(value="/user/")
		 public ModelAndView index2(ModelAndView mv){
			mv.setViewName("/user/list");
			return mv;
		}

		// 如果在目录下输入任何不存在的参数，则跳转到list
		@RequestMapping(value="/user/{formName}")
		 public String index2(@PathVariable String formName){
			String blank = "/user/list";
			return blank;
		}

		//查询所有用户显示用户列表
		@RequestMapping(value="/user/list",method=RequestMethod.GET)
		 public String index(Integer pageIndex, Model model, String content, User user){
			// 创建分页对象
		    PageModel pageModel = new PageModel();
		    if(pageIndex != null){
			pageModel.setPageIndex(pageIndex);
			}
			List<User> user_list = hrmService.get_UserList(user,pageModel);
			Integer count = 0;
			if (content!=null&&!content.equals("")){
				count = hrmService.countUser(content);
				user_list = hrmService.get_UserLikeList(content);
			}
			model.addAttribute("count",count);
			model.addAttribute("list",user_list);
			model.addAttribute("pageModel", pageModel);
			return "user/list";
		}


		@RequestMapping(value="/user/toadd",method=RequestMethod.GET)
		 public String add(Model model,Integer id){
			if(id!=null){
				User user = hrmservice.findUserById(id);
				model.addAttribute("job",user);
			}
			return "/user/add";
		}

		//用户更新页面跳转
		@RequestMapping(value="/user/edit",method=RequestMethod.GET)
		 public String edit(Model model,Integer id){
			if(id!=null){
				User user = hrmservice.findUserById(id);
				user.setPassword(user.getPassword().substring(0, 6));
				model.addAttribute("user",user);
			}

			List<Status>  status_list = hrmservice.findAllStatus();
			model.addAttribute("status_list", status_list);
			return "/user/edit";
		}

		//用户更新操作
		@RequestMapping(value="/user/edit",method=RequestMethod.POST)
		 public String toedit(Integer status_id,Integer pageIndex,Model model,Integer id,@ModelAttribute User user){

				PageModel pageModel = new PageModel();
				if(pageIndex != null){
						pageModel.setPageIndex(pageIndex);
				}
		    	this.genericAssociation(status_id,user);
			    hrmservice.modifyUser(user);

				List<User> user_list = hrmservice.get_UserList(user,pageModel);
				model.addAttribute("list",user_list);
				model.addAttribute("pageModel", pageModel);
				return "redirect:/user/list";
		}


		//用户注册
		@RequestMapping(value="/user/add",method=RequestMethod.POST)
		 public ModelAndView add(ModelAndView mv,@ModelAttribute User user ,Integer id){
			    //1.首先登录名进行判断，如果登录名已经存在，将不能进行插入
			    User user1 = hrmservice.findUserByLoginAndName(user.getLoginname(), user.getUsername());
			    User user2 = hrmservice.findUserByLogin(user.getLoginname());
			    User user3 = hrmservice.findUserByName(user.getUsername());
			    if(user1==null&&user2==null&&user3==null) {
			    	//检查邮箱是否已经被注册
			    	//通过用户信息提交的邮箱号去user_inf表中去查询是否有邮箱所对应的用户
			    	User user4 = hrmservice.findUserByEmail(user.getEmail());
			    	if(user4==null) {
			    	//对明文密码进行加密
				    user.setPassword(ShiroMD5Privacy.privacy(user.getLoginname(), user.getPassword()));
				  //这个地方需要生成一个id，这个id是为了给che_id,sal_id,con_id 提供的一个值
				    //那这个id该如何去生成，怎么就能唯一呢
				    //可以去随机生成一4位数的数字，生成之后，这个数字必须保证唯一，所以，先生成数字，再去user_inf表中去查找看存不存在
				    //如果不存在，就可以将这个数字设置为id，否则，继续去生成，完成之后，就可以进行插入操作了
				       //这里随机生成的数字不能确保唯一性，所以，定义一个全局的id，这个id初始化的值每次需要从数据库获取到，确保唯一
				      CreateStaticId createStaticId = new CreateStaticId(ahualyservice.getStaticId().getStaticId());
				      Integer staticId=createStaticId.getStaticId();
				      System.out.println("插入之前staticId==="+staticId);
					    	user.setEmp_id(staticId);
					    	user.setChe_id(staticId);
					    	user.setCon_id(staticId);
					    	user.setSal_id(staticId);
						hrmservice.addUser(user);
					  //插入成功之后，这里执行更新工作，就是将这个值更新掉
						hrmservice.updata_staticId(staticId);
					  System.out.println("插入之后staticId==="+staticId);
					//在注册成功之后，我需要通过获取邮箱信息给用户发送邮件，告诉用户管理员会在2小时之内进行身份审核
					//审核完之后，会发送邮件给用户，用户就可以登录系统了
					mv.setViewName("redirect:/user/list");
				    return mv;
			    	}
			    	else {
			    		mv.addObject("message", "此邮箱已被注册，请更换你的邮箱");
			    		mv.setViewName("redirect:/user/toadd");
						return mv;
			    	}

			    }else {
			    	mv.addObject("message", "此用户已经被注册，请更换你的用户名和登录名");
			    	mv.setViewName("redirect:/user/toadd");
					return mv;
			    }
		}

		@RequestMapping(value="/user/delete",method=RequestMethod.GET)
		 public void delete(Integer id){
			System.out.println(id);
			if(id!=null){
				hrmservice.removeUserById(id);
			}
		}

		private void genericAssociation(Integer status_id,User user){

			if(status_id != null){
				Status status = new Status();
				status.setId(status_id);
				user.setStatus(status);
			}
		}*/
}
